﻿package little.bunny;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
//import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.TableLayout;  
import android.widget.TableRow; 
import android.widget.TableRow.LayoutParams; 

public class CustClothesTrace extends Activity{
	private Button okButton;
	private EditText txtInputWorkNo;
	private Button backButton;
	private Button myButton;
	
	private final String serviceNameSpace = "http://littlebunny.com/";
	private final String method_name = "GetClothesTrace";
	private final String serviceUrl = "http://www.littlebunny.com.cn/bunny_service/bunny_service.asmx";
	private final String SOAP_ACTION = "http://littlebunny.com/GetClothesTrace";
		
	private int[] ColumnWidths = new int[]{40, 20, 40};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cust_cloth_trace);

		//textShowXiaoFei = (TextView) findViewById(R.id.textShowXiaoFei);
		txtInputWorkNo = (EditText) findViewById(R.id.editInputWorkNo);
		TextView txtinfo = (TextView) findViewById(R.id.textShowTrace);
		myButton = (Button) findViewById(R.id.btn_list_title);
		okButton = (Button) findViewById(R.id.btnsearch_trace);
		
		myButton.setText("衣物跟踪");
		
		txtinfo.setText("");
		init_header();
		
		//*************测试数据************
		//txtInputWorkNo.setText("C388000458");
		//**************************
		
		okButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				get_clothes_trace();
			}
		});
		
		backButton = (Button) findViewById(R.id.back_button);
		backButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	private void get_clothes_trace()
	{
		String card_id = txtInputWorkNo.getText().toString();
		TextView txtinfo = (TextView) findViewById(R.id.textShowTrace);
		//card_id:0755018369

		if (card_id.length() == 0) {
			txtinfo.setText("请输入洗衣单号码.");
			return;
		}

		if (NetFunction.CheckNetStatus(this)==false)
		{
			txtinfo.setText("没有找到有效的网络.");
			return;
		}
		
		txtinfo.setText("");
		//txtinfo.setText("开始从服务器读取会员消费记录...");

		Toast.makeText(this, "从服务器读取衣物跟踪记录...", Toast.LENGTH_LONG).show();
		
		final ProgressDialog progressDialog = ProgressDialog.show(this, "请稍等",
				"数据加载中...", true);
		
		progressDialog.setOnKeyListener(new OnKeyListener() {
			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_BACK){
					progressDialog.dismiss();
				}
				return false;
			}
		});
		
		Thread networkThread = new Thread() {
			@Override
			public void run() {
				TextView txtno = (EditText) findViewById(R.id.editInputWorkNo);
								
				SoapObject request = new SoapObject(serviceNameSpace, method_name);
				request.addProperty("work_no", txtno.getText().toString());
				
				SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
				envelope.dotNet = true;
				envelope.setOutputSoapObject(request);
				
				try {
					HttpTransportSE ht = new HttpTransportSE(serviceUrl);
					ht.call(SOAP_ACTION, envelope);

					final SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
					final String result = response.toString();
					
					// Toast.makeText(this, "读取完毕.", Toast.LENGTH_LONG).show();

					progressDialog.dismiss();
					
					runOnUiThread(new Runnable() {
						public void run() {
							if (result.startsWith("99:", 0))
							{
								TextView txtshow;
								txtshow = (TextView) findViewById(R.id.textShowTrace);
								txtshow.setText(result.substring(3));
							}
							else
								show_data(result);
							//TextView txtshow;
							//txtshow = (TextView) findViewById(R.id.textShowXiaoFei);
							//txtshow.setText(result);
						}
					});
				} catch (Exception e) {
					progressDialog.dismiss();
					e.printStackTrace();
					TextView txt1;
					txt1 = (TextView) findViewById(R.id.textShowTrace);
					txt1.setText("网络错误");
					/*
					if (e.getMessage().indexOf("Host")>-1)
					{
						new AlertDialog.Builder(CustClothesTrace.this)
						.setTitle("网络信号异常")
						.setMessage("请查看网络连接，请稍后再试...")
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										CustClothesTrace.this.finish();
									}
								}).show();
					}
					*/
				}
			}
		};

		networkThread.start();
		
	}
		
	// run when the button is clicked  
    private void show_data(String result_data) {  
    	String[] temp = null;
    	int fixedRowHeight = 30;
    	try
    	{
    		temp = result_data.split("\\|");  
        	
        	TableLayout table = (TableLayout) findViewById(R.id.TableLayout02);
        	table.removeAllViews();
        	int len = temp.length;
        	        	
            for (int i = 0; i < len; i++) {
            	//String s1="10.6~0.02~2012-10-10-20~C186045454";
            	String[] d_row = temp[i].split("~");
            	
            	TableRow row = new TableRow(this);
            	
                //row.setBackgroundDrawable(drawable);
                
                row.addView(makeTableRowWithText(d_row[0], ColumnWidths[0], fixedRowHeight));
                row.addView(makeTableRowWithText(d_row[1], ColumnWidths[1], fixedRowHeight));
                row.addView(makeTableRowWithText(d_row[2], ColumnWidths[2], fixedRowHeight));
                            
            	table.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            }
    	}
    	catch (Exception e) {
			e.printStackTrace();
			TextView txt1;
			txt1 = (TextView) findViewById(R.id.textShowTrace);
			txt1.setText(e.getMessage());
		}
    }
    
    private void init_header()
    {
    	TableRow.LayoutParams wrapWrapTableRowParams = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);  
    	wrapWrapTableRowParams.setMargins(1, 3, 1, 1);
    	
        int fixedRowHeight = 25;  
        TableRow row = new TableRow(this);  
        
        TableLayout header = (TableLayout) findViewById(R.id.table_header);
        
        row.setLayoutParams(wrapWrapTableRowParams);  
        row.setGravity(Gravity.CENTER);
        
        Resources resource = this.getBaseContext().getResources();
		Drawable drawable=resource.getDrawable(R.drawable.test_list_bg);
        row.setBackgroundDrawable(drawable);
                		
        row.addView(makeTableRowWithText("衣物名称", ColumnWidths[0], fixedRowHeight));
        row.addView(makeTableRowWithText("状态", ColumnWidths[1], fixedRowHeight));  
        row.addView(makeTableRowWithText("操作时间", ColumnWidths[2], fixedRowHeight));  
        
        header.addView(row);  	
    }
    
    private TextView recyclableTextView;
    
    private TextView makeTableRowWithText(String text, int widthInPercentOfScreenWidth, int row_height) {  
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        
        recyclableTextView = new TextView(this);  
        recyclableTextView.setText(text);
          
        recyclableTextView.setTextColor(Color.BLACK);  
        //recyclableTextView.setTextSize(12);  
        recyclableTextView.setWidth(widthInPercentOfScreenWidth * screenWidth / 100);  
        //recyclableTextView.setHeight(row_height);
        
        return recyclableTextView;  
    }
}
